/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        //递归结束条件
        if(head == null || head.next == null) return head;

        //找到链表中间节点并断开链表
        ListNode mid = findMid(head);
        ListNode rightNode = mid.next;
        mid.next = null;
        
        //归并
        ListNode left = sortList(head);
        ListNode right = sortList(rightNode);
        return mergeSortedList(left,right);;
    }

    public ListNode findMid(ListNode head){
        if(head == null) return null;
        if(head.next.next == null) return head;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    
    public ListNode mergeSortedList(ListNode head1,ListNode head2){
        ListNode newHead = new ListNode(-1);
        ListNode cur = newHead;
        while(head1 != null && head2 != null){
            if(head1.val > head2.val){
                cur.next = head2;
                head2 = head2.next;
            }else{
                cur.next = head1;
                head1 = head1.next;
            }
            cur = cur.next;
        }
        if(head1 == null){
           cur.next = head2;
        }else{
           cur.next = head1;
        }
      return newHead.next;
    }

}